<?php

namespace library\Core;

class WebApplication {

    public $defaultController = 'Site'; //默认控制器
    public $defaultAction = 'index'; //默认方法
    private $defaultActionFix = 'action'; //默认方法前缀

    public function run() {
        $route = null;
        $param = [];
        if (isset($_GET['r'])) {
            $route = $_GET['r'];
            foreach ($_GET as $key => $value) {
                $key !== 'r' ? $param[$key] = $value : null;
            }
        }
        $routeArr = $this->processRoute($route);
        $this->runController($routeArr, $param);
    }

    /**
     * 处理路由
     * @param string $route
     * @return array
     */
    private function processRoute($route = null) {
        $routeArr = explode('/', $route);
        $routeArr[0] = "\application\Controller\\" . (!empty($routeArr[0]) ? ucfirst($routeArr[0]) : ucfirst($this->defaultController)) . "Controller";
        $routeArr[1] = $this->defaultActionFix . (!empty($routeArr[1]) ? ucfirst($routeArr[1]) : ucfirst($this->defaultAction));
        return $routeArr;
    }

    /**
     * 实例化控制器与调用对应方法
     * @param array $routeArr
     * @param array $param
     * @return type
     * @throws Exception
     */
    private function runController($routeArr = [], $param = []) {
        if (class_exists($routeArr[0])) {
            $controller = new $routeArr[0]();
            $action = $routeArr[1];
            $actions = explode('-', $action);
            if (count($actions) > 1) {
                $action = '';
                foreach ($actions as $key => $value) {
                    if ($key) {
                        $action .= ucfirst($value);
                    } else {
                        $action .= $value;
                    }
                }
            }
            if (method_exists($controller, $action)) {
                return call_user_func_array([$controller, $action], $param);
            } else {
                throw new \Exception('方法不存在');
            }
        } else {
            $controller = new \application\Controller\SiteController();
            return call_user_func_array([$controller, 'actionError'], $param);
        }
    }

}
